package com.example.ying.controller;

import com.example.ying.common.R;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.WebAttributes;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@RestController
public class LoginController {

    @GetMapping("/login/error")
    public R loginError(HttpServletRequest request) {
        AuthenticationException authenticationException = (AuthenticationException) request.getSession().getAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);

        if (authenticationException instanceof UsernameNotFoundException || authenticationException instanceof BadCredentialsException) {
            return R.error("用户名或密码错误");
        } else if (authenticationException instanceof DisabledException) {
            return R.error("用户已被禁用");
        } else if (authenticationException instanceof LockedException) {
            return R.error("账户被锁定");
        } else if (authenticationException instanceof AccountExpiredException) {
            return R.error("账户过期");
        } else if (authenticationException instanceof CredentialsExpiredException) {
            return R.error("证书过期");
        } else {
            return R.error("登录失败");
        }
    }
}
